package com.attendance.www.hr.exception;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zhangkongli.frame.core.FaultData;
import com.zhangkongli.frame.core.ResultMap;

@Configuration
@PropertySource("classpath:/errorCode.properties")
@ControllerAdvice
public class GlobalExceptionHandle {
	
	@Autowired
    private Environment env;

	@ExceptionHandler(Exception.class)
	@ResponseBody
	public Object handleAllException(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex) {
		ex.printStackTrace();  
        StringWriter sw = new StringWriter();  
        ex.printStackTrace(new PrintWriter(sw, true));  
        String str = sw.toString();  
    	Logger.getLogger(this.getClass()).error("错误信息" + "==>" + str);
		return ResultMap.fault("00001", "无法处理请求，请联系管理员！");
	}
	
//	@ExceptionHandler(SQLException.class)
//	public String handleSQLException(HttpServletRequest request, Exception ex) {
//		return "database_error";
//	}

//	@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "IOException occured")
//	@ExceptionHandler(IOException.class)
//	public void handleIOException() {
//		// returning 404 error code
//	}
	
	@ExceptionHandler(ResultFaultException.class)
	public Object handleResultFaultException(ResultFaultException e) throws IllegalStateException, UnsupportedEncodingException {
		
		if(e.getResult()!=null){
			List<FaultData> faultDataList = new ArrayList<FaultData>();
			for(Map.Entry<String, Object>entry : e.getResult().entrySet()){
				FaultData faultData = new FaultData();
				faultData.setCode(entry.getKey());
				faultData.setMessage(new String(env.getRequiredProperty(entry.getKey()).getBytes("ISO-8859-1"),"UTF-8"));
				faultData.setErrorData(entry.getValue());
				faultDataList.add(faultData);
			}
			return ResultMap.fault(faultDataList);
		}
		return ResultMap.fault(e.getMessage(),new String(env.getRequiredProperty(e.getMessage()).getBytes("ISO-8859-1"),"UTF-8"));
	}
	
	/*http://www.journaldev.com/2651/spring-mvc-exception-handling-exceptionhandler-controlleradvice-handlerexceptionresolver-json-response-example*/
}
